const axios = require("axios");
const Joi = require("joi");
const appleReceiptVerify = require("node-apple-receipt-verify");
module.exports = class IOSVerifier extends colpu.Controller {
  constructor(ctx) {
    super(ctx);
    const {
      config: { iospay },
    } = ctx;
    appleReceiptVerify.config({
      secret: iospay.sharedKey,
      environment: ["production", "sandbox"],
    });
  }

  async order(ctx) {
    await ctx.validateAsync({
      body: {
        serverVerificationData: Joi.string().required(),
        purchaseID: Joi.string().required(),
      },
      status: 10001,
    });
    const body = ctx.request.body;
    const res = await this._verify(body);
    console.log(body.purchaseID, res);
    ctx.respond(res);
  }

  /**
   * @function verify
   * @params tokens 为客户端购买时苹果服务器返回的订单信息.
   * orderId 为购买的订单ID.
   */
  _verify(data) {
    return appleReceiptVerify.validate({
      receipt: data.serverVerificationData,
    });
  }
};
